package org.bigdata.framework.admin.web.controller;


import java.text.SimpleDateFormat;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.bigdata.framework.core.model.Dict;
import org.bigdata.framework.core.model.Member;
import org.bigdata.framework.core.model.User;
import org.bigdata.framework.core.model.Workflow;
import org.bigdata.framework.core.model.WorkflowNode;
import org.bigdata.framework.core.protocol.ILiveService;
import org.bigdata.framework.core.protocol.IPublicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

@Controller
public class WorkflowController extends BaseContoroller{
	@Autowired
	private IPublicService publicService;
	
    // 前往工作流管理页面
    @RequestMapping("show-knowledge-workflow.html")
    public String roomToMedia() {
    	return "/modules/repository/show_knowledge_workflow";
    }
    // 前往工作流管理页面
    @RequestMapping("show-knowledge-workflow-view.html")
    public String roomToMediaview(HttpServletRequest request,
 			HttpServletResponse response) {
    	String id = request.getParameter("id");
    	Workflow workflow = publicService.findWorkflow(Integer.parseInt(id));
    	request.setAttribute("jsondata", workflow.getJsonData());
    	request.setAttribute("workFlowId",id);
    	return "/modules/repository/show_knowledge_workflow_view";
    }
    // 前往添加修改界面
    @RequestMapping("workflow_add_update.html")
    public String workflowAddUpdate() {
    	return "/modules/repository/workflow_add_update";
    }
    // 前往节点添加修改界面
    @RequestMapping("mulu_edit.html")
    public String muluEdit() {
    	return "/modules/workflow/mulu_edit";
    }
    // 前往节点选择执行人
    @RequestMapping("workflow-node-user.html")
    public String nodeUser() {
    	return "/modules/repository/workflow_node_user";
    }
    // 跳转回工作流管理页面
    @RequestMapping("locationJump.html")
    public String locationJump() {
    	return "/modules/repository/show_knowledge_workflow";
    }
    // 前往可视化页面
    @RequestMapping("technological.html")
    public String technological(HttpServletRequest request,
 			HttpServletResponse response) {
    	String id = request.getParameter("id");
    	Workflow workflow = publicService.findWorkflow(Integer.parseInt(id));
    	request.setAttribute("jsondata", workflow.getJsonData());
    	request.setAttribute("workFlowId",id);
    	return "/modules/workflow/1";
    }
    // 工作流查询
 	@RequestMapping("findWorkflow")
 	@ResponseBody
 	public void findWorkflow(HttpServletRequest request,
 			HttpServletResponse response) throws Exception {
 		// System.out.println("findallDict");
 		Integer pageNumber = 15;
 		Integer pageSize = 1;
 		if (request.getParameter("page") != null) {
 			pageSize = Integer.parseInt(request.getParameter("page"));
 		} else {
 			pageSize = 1;
 		}
 		//关键词
 		String queryParam = request.getParameter("queryParams");
 		//检索
 		String text = request.getParameter("text");
 		HashMap<String, Object> queryParams = new HashMap<String, Object>();
 		if (text != null && !"".equals(text)) {
 			queryParams.put("%," + queryParam, text);
 		}
 		Integer count = publicService.getWorkflowCount(queryParams);
 		List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();
 		LinkedHashMap<String, Object> mp = null;
 		List<Workflow> list = publicService.getWorkflow(queryParams, pageSize,pageNumber);
 		//List<Workflow> WorkflowAll = publicService.getWorkflow();
 		for (int i = 0; i < list.size(); i++) {
 			Workflow workflow = list.get(i);
 			if (workflow != null) {
 				mp = new LinkedHashMap<String, Object>();
 				mp.put("id", workflow.getId());
 				mp.put("nameZh", workflow.getNameZh());
 				mp.put("nameEn", workflow.getNameEn());
 				mp.put("description", workflow.getDescription());
 				mp.put("classesEn", workflow.getClassesEn());
 				mp.put("createUser", workflow.getCreateUser());
 				mp.put("createTime", workflow.getCreateTime());
 				if(workflow.getStatus().equals(0)){
 					mp.put("status", "未开启");
 				}else{
 					mp.put("status", "已开启");
 				}
 				mp.put("jsonData", workflow.getJsonData());
 				r.add(mp);
 			}
 		}
 		String result = formatToJson(r);
 		// System.out.println("result:" +result);
 		StringBuffer sb = new StringBuffer();
 		int listsize = list.size();
 		sb.append("{\"listsize\":" + listsize + ",");
 		sb.append("\"pageSize\":"+ (int) Math.ceil(Double.valueOf(count) / pageNumber) + ",");
 		sb.append("\"result\":" + result);
 		sb.append("}");
 		super.pringWriterToPage(sb.toString(), "application/json", response);
 	}
 	// 增加/修改
 	@RequestMapping("workflowAddandUpdate")
 	@ResponseBody
 	public void workflowAddandUpdate(HttpServletRequest request,
 			HttpServletResponse response) throws Exception {
 		String id= request.getParameter("id");
 		String nameZh = request.getParameter("nameZh");
 		String nameEn = request.getParameter("nameEn");
 		String description = request.getParameter("description");
 		String classes_en = request.getParameter("classes_en");
 		if(classes_en.indexOf("(")!=-1){
 			classes_en = classes_en.substring(classes_en.indexOf("("),classes_en.length());
 		}
 		if(classes_en.indexOf(")")!=-1){
 			classes_en = classes_en.substring(0,classes_en.indexOf(")"));
 		}
 		classes_en=classes_en.replace("(", "");
 		classes_en=classes_en.replace(")", "");
 		//String createUser = request.getParameter("createUser");
 		//String createTime = request.getParameter("createTime");
 		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	 	String createTime = df.format(new Date());
 		String status = request.getParameter("status");
 		User user = publicService.findUser((Integer) request.getSession().getAttribute("userid"));
 		String nickname = user.getUsername();
 		Workflow wf = new Workflow();
 		if(!id.equals("0") && id != null){
 	 		Workflow workflow = publicService.findWorkflow(Integer.parseInt(id));
 			workflow.setNameZh(nameZh);
 	 		workflow.setNameEn(nameEn);
 	 		workflow.setDescription(description);
 	 		workflow.setClassesEn(classes_en);
 	 		workflow.setCreateUser(nickname);
 	 		workflow.setStatus(Integer.parseInt(status));
 	 		Map<String, String> map = (Map<String, String>)JSON.parse(workflow.getJsonData());
 	 		map.put("title",nameZh);
 	 		String jsonData = JSON.toJSONString(map);
 	 		workflow.setJsonData(jsonData);
 	 		wf = publicService.editWorkflow(workflow);
 		}else if(id.equals("0")){
 			Workflow workflow =new Workflow();
 	 		workflow.setNameZh(nameZh);
 	 		workflow.setNameEn(nameEn);
 	 		workflow.setDescription(description);
 	 		workflow.setClassesEn(classes_en);
 	 		workflow.setCreateUser(nickname);
 	 		workflow.setCreateTime(createTime);
 	 		//workflow.setCreateTime(createTime);
 	 		workflow.setStatus(Integer.parseInt(status));
 	 		workflow.setJsonData("{\"title\":\""+nameZh+"\",\"nodes\":{\""
 	 				+ "demo2_node_1\":{\"name\":\"开始\",\"left\":129,\"top\":109,\"type\":\"start round\",\"width\":24,\"height\":24,\"alt\":true},\"demo2_node_2\":{\"name\":\"结束\",\"left\":564,\"top\":106,\"type\":\"end round\",\"width\":24,\"height\":24,\"alt\":true}},\"lines\":{},\"areas\":{},\"initNum\":3"
 	 				+ "}");
 	 		wf = publicService.saveWorkflow(workflow);
 		}
 		String result = formatToJson(wf);
		super.pringWriterToPage(result.toString(), "application/json", response);
 	}
 	//删除
 	@RequestMapping("delworkflow")
 	public void delworkflow(HttpServletRequest request,
 			HttpServletResponse response) throws Exception {
 		String id = request.getParameter("id");
 		
		Workflow findWorkflow = publicService.findWorkflow(Integer.parseInt(id));
		boolean falg = false;
		if(findWorkflow!=null){
			publicService.deleteWorkflow(findWorkflow);
			HashMap<String, Object> workflowNodeMap = new HashMap<String, Object>();
			workflowNodeMap.put("=,workflowId", Integer.parseInt(id));
			List<WorkflowNode> workflowNode = publicService.getWorkflowNode(workflowNodeMap,1,99);
			for(WorkflowNode wfn : workflowNode){
				publicService.deleteWorkflowNode(wfn);
			}
			falg=true;
		}
 		String result = "{\"count\":" + falg + "}";
 		super.pringWriterToPage(result.toString(), "application/json", response);
 	}
 	 //可视化页面保存
 	 @RequestMapping("saveWorkflowView")
 	 public void saveWorkflowView(HttpServletRequest request,
 	 			HttpServletResponse response) throws Exception {
 		String jsonData = request.getParameter("jsondata");
 		String id = request.getParameter("id");
 		Workflow workflow = publicService.findWorkflow(Integer.parseInt(id));
 		boolean falg = false;
 		if(workflow!=null&&id!=null){
 			workflow.setJsonData(jsonData);
 	 		publicService.editWorkflow(workflow);
 	 		falg=true;
 		}
 		String result = "{\"count\":" + falg + "}";
 		super.pringWriterToPage(result.toString(), "application/json", response);
 	 }
 	
 	// 数据回显
 	@RequestMapping("workflowfindone")
 	public void toDictFindOne(HttpServletRequest request,
 			HttpServletResponse response) throws Exception {
 		String id = request.getParameter("id");
 		HashMap<String, Object> workflowMap = new HashMap<String, Object>();
 		Workflow workflow = publicService.findWorkflow(Integer.parseInt(id));
 		if (workflow != null) {
 			workflowMap.put("nameZh", workflow.getNameZh());
 			workflowMap.put("nameEn", workflow.getNameEn());
 			workflowMap.put("description", workflow.getDescription());
 			workflowMap.put("classesEn", workflow.getClassesEn());
 			workflowMap.put("createUser", workflow.getCreateUser());
 			workflowMap.put("createTime", workflow.getCreateTime());
 			workflowMap.put("status", workflow.getStatus());
 		}
 		String result = formatToJson(workflowMap);
 		// System.out.println("result  dict 获取更新内容:"+result);
 		super.pringWriterToPage(result.toString(), "application/json", response);
 	}
 	// 节点数据回显
 	@RequestMapping("workflowNodeDataRetrieval")
 	public void workflowNodeDataRetrieval(HttpServletRequest request,
 			HttpServletResponse response) throws Exception {
 		String workflowId = request.getParameter("workflowId");
 		String workflowNodeName = request.getParameter("executor");
 		String str=new String((request.getParameter("executor")).getBytes("iso-8859-1"),"utf-8"); 
 		HashMap<String, Object> workflowNodeMap = new HashMap<String, Object>();
		workflowNodeMap.put("=,nodeName", workflowNodeName);
		workflowNodeMap.put("=,workflowId", workflowId);
		List<WorkflowNode> workflowNode = publicService.getWorkflowNode(workflowNodeMap,1,10);
		HashMap<String, Object> workflowNodeMaps = new HashMap<String, Object>();
		for(WorkflowNode wfn : workflowNode){
			workflowNodeMaps.put("wfnodeName", wfn.getNodeName());
			workflowNodeMaps.put("wfCreateUser", wfn.getCreateUser());
			workflowNodeMaps.put("wfNodeDescription", wfn.getNodeDescription());
		}
 		String result = formatToJson(workflowNodeMaps);
 		// System.out.println("result  dict 获取更新内容:"+result);
 		super.pringWriterToPage(result.toString(), "application/json", response);
 	}
 	// 节点数据删除
 	@RequestMapping("deleteWorkflowNode")
 	public void deleteWorkflowNode(HttpServletRequest request,
 			HttpServletResponse response) throws Exception {
 		String workflowId = request.getParameter("workflowId");
 		String workflowName = request.getParameter("workflowName");
 		//String workflowNodeName = request.getParameter("workflowNodeName");
 		
 		HashMap<String, Object> workflowNodeMap = new HashMap<String, Object>();
 		workflowNodeMap.put("=,nodeName", workflowName);
 		workflowNodeMap.put("=,workflowId", workflowId);
 		//workflowNodeMap.put("=,nodename", workflowNodeName);
 		List<WorkflowNode> workflowNode = publicService.getWorkflowNode(workflowNodeMap,1,10);
 		int istype = 1;
 		if(null == workflowNode || workflowNode.size() ==0 ){
 			istype=0;
 			String result = "{\"istype\":" + istype + "}";
 	 		super.pringWriterToPage(result.toString(), "application/json", response);
		}
 		for(WorkflowNode wfn : workflowNode){
 			publicService.deleteWorkflowNode(wfn);
 			istype=0;
 		}
 		String result = "{\"istype\":" + istype + "}";
 		super.pringWriterToPage(result.toString(), "application/json", response);
 	}
 	// 节点数据添加及修改
 	@RequestMapping("workflowNodeAddUpdata")
 	public void workflowNodeAddUpdata(HttpServletRequest request,
 			HttpServletResponse response) throws Exception {
 		String id = request.getParameter("id");
 		String type = request.getParameter("type");
 		String nodeName = request.getParameter("nodeName");
 		String nodeText = request.getParameter("nodeText");
 		String workFlowId = request.getParameter("workFlowId");
 		String nodeUser = request.getParameter("nodeUser");
 		//String classesen = request.getParameter("classes_en");
 		String falg = "0";
 		Workflow findWorkflow = publicService.findWorkflow(Integer.parseInt(workFlowId));
 		//资源库
 		String classesen =findWorkflow.getClassesEn();
 		User user = publicService.findUser((Integer) request.getSession().getAttribute("userid"));
 		//创建人
 		String nickname = user.getUsername();
 		//当前时间
 		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	 	String createTime = df.format(new Date());
 		HashMap<String, Object> wfnCount = new HashMap<String, Object>();
 		wfnCount.put("=,workflowId",workFlowId);
 		int workflowNodeCount = publicService.getWorkflowNodeCount(wfnCount);
 		HashMap<String, Object> wfnmap = new HashMap<String, Object>();
 		wfnmap.put("=,nodeName",nodeName);
 		wfnmap.put("=,workflowId",workFlowId);
 		List<WorkflowNode> workflowNodes = publicService.getWorkflowNode(wfnmap,1,10);
 		
 		//节点名称不能重复
 		if(workflowNodes!=null && workflowNodes.size()!=0&&!type.equals("0")){
 			String result = "{\"count\":" + falg + "}";
	 		super.pringWriterToPage(result.toString(), "application/json", response);
 		}
 		else if(!type.equals("0") && type != null){ 			
 			WorkflowNode wn = new WorkflowNode();
 			wn.setWorkflowId(Integer.parseInt(workFlowId));
 			wn.setNodeName(nodeName);
 			wn.setNodeDescription(nodeText);
 			wn.setClassesEn(classesen);
 			wn.setCreateUser(nickname);
 			wn.setExecutor(nodeUser);
 			wn.setSort(workflowNodeCount+1);
 			wn.setCreateTime(createTime);
 			publicService.saveWorkflowNode(wn);
 			falg = "1";
 		}else if(type.equals("0")){
 			HashMap<String, Object> workflowNodeMap = new HashMap<String, Object>();
 			workflowNodeMap.put("=,nodeName",nodeName);
 			workflowNodeMap.put("=,workflowId",workFlowId);
 			
 			List<WorkflowNode> workflowNode = publicService.getWorkflowNode(workflowNodeMap,1,10);
 			if(workflowNode!=null && workflowNode.size()!=0){
 				for(WorkflowNode wf : workflowNode){
 	 				wf.setWorkflowId(Integer.parseInt(workFlowId));
 	 				wf.setNodeName(nodeName);
 	 				wf.setNodeDescription(nodeText);
 	 				wf.setCreateUser(nickname);
 	 				wf.setExecutor(nodeUser);
 	 				publicService.editWorkflowNode(wf);
 	 				falg = "1";
 	 			}
 			}else{
 				WorkflowNode wn = new WorkflowNode();
 	 			wn.setWorkflowId(Integer.parseInt(workFlowId));
 	 			wn.setNodeName(nodeName);
 	 			wn.setNodeDescription(nodeText);
 	 			wn.setClassesEn(classesen);
 	 			wn.setCreateUser(nickname);
 	 			wn.setExecutor(nodeUser);
 	 			wn.setSort(workflowNodeCount+1);
 	 			wn.setCreateTime(createTime);
 	 			publicService.saveWorkflowNode(wn);
 	 			falg = "1";
 			}
 			
 		}
 			String result = "{\"count\":" + falg + "}";
	 		super.pringWriterToPage(result.toString(), "application/json", response);
 	}
 	@RequestMapping("listfinduser")
	@ResponseBody
	public void memberfindAll(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Integer pageNumber = 10;
		Integer pageSize = Integer.parseInt(request.getParameter("page"));
		String username = request.getParameter("username");
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		if(username != null && !"".equals(username)){
			queryParams.put("%,username", username);
		}
		Integer count = publicService.getUserCount(queryParams);
		List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();
		LinkedHashMap<String, Object> mp = null;
		List<User> list = publicService.getUser(queryParams, pageSize,
				pageNumber);
		for (int i = 0; i < list.size(); i++) {
			User user = list.get(i);
			mp = new LinkedHashMap<String, Object>();
			mp.put("id", user.getId());
			mp.put("username", user.getUsername());
			mp.put("password", user.getPassword());
			mp.put("nickname", user.getNickname());
			mp.put("createTime", user.getCreateTime());
			mp.put("email", user.getEmail());
			mp.put("address", user.getAddress());
			mp.put("isPrincipal", user.getIsPrincipal());
			mp.put("signature", user.getSignature());
			mp.put("departmentId", user.getDepartmentId());
			mp.put("telephone", user.getTelephone());
			String date = "null";
			if (user.getCreateTime() != null
					&& !user.getCreateTime().equals("")) {
				date = user.getCreateTime();
			}
			mp.put("createTime", date);
			r.add(mp);
		}

		String result = formatToJson(r);
		StringBuffer sb = new StringBuffer();
		int listsize = r.size();
		sb.append("{\"listsize\":" + listsize + ",");
		sb.append("\"pageSize\":"
				+ (int) Math.ceil(Double.valueOf(count) / pageNumber) + ",");
		sb.append("\"result\":" + result);
		sb.append("}");
		super.pringWriterToPage(sb.toString(), "application/json", response);
	}

	public List getJsonString(String jsonData,int workflowId) {
	    JSONObject jsonObject = new JSONObject(jsonData);
 		JSONObject object = (JSONObject)jsonObject.get("lines");
 		ArrayList <String> list = new ArrayList<String>();
 		list.add("demo2_node_1");
 		String a = "demo2_node_1";
 		for(int b = 0 ;b<object.length();b++){
 			Iterator iterator = object.keys();
 			while(iterator.hasNext()){
	 			JSONObject objectone = (JSONObject)object.get((String)iterator.next());
	 			String node1 = objectone.getString("from");
	 			if(node1.equals(a)){
	 				list.add(objectone.getString("to"));
	 			}
 			}
 			a=list.get(list.size()-1);
 		}
 		ArrayList <String> listtwo = new ArrayList<String>();
 		JSONObject objecttwo = (JSONObject)jsonObject.get("nodes");
 		for(int i = 0 ;i<list.size();i++){
 			JSONObject objectone = (JSONObject)objecttwo.get((String)list.get(i));
 			String name = objectone.getString("name");
 			listtwo.add(name);
 		}
 		ArrayList <Integer> endList = new ArrayList<Integer>();
 		for(String name :listtwo){
 			HashMap<String, Object> queryParams = new HashMap<String, Object>();
 			queryParams.put("=,nodeName",name);
 			queryParams.put("=,workflowId", workflowId);
 			List<WorkflowNode> workflowNode = publicService.getWorkflowNode(queryParams,1,99);
 			if(workflowNode!=null){
 				endList.add(workflowNode.get(0).getId());
 			}
 		}
 		return endList;
 	}
}
